const { validateForeignKey } = require('../models/foreignKeyVis');
const { commentCountChange } = require('../services/blogService');
const { createService, removeService, findAll, findByIdService, removeByBlogIdService } = require('../services/messageService');
const AppError = require('../utils/AppError');
const Controller = require('../utils/Controller');
const { toi, to, sendResult } = require('../utils/tools');

class BlogTypeController extends Controller {
	async create(req, res, next) {
		const schema = req.joi.object({
			nickname: req.joi.string().required(),
			content: req.joi.string().required(),
			createDate: req.joi.date(),
			blogId: req.joi.number().external(validateForeignKey('blog'))
		});
		const [failed] = await to(schema.validateAsync(req.body));
		if (failed) return next(new AppError(failed, 400));
		req.body.avatar = '/static/avatar/rainbow.gif';

		// 创建评论或留言
		const [error, result] = await to(createService(req.body));
		if (error) return next(new AppError(error, 400));

		// 如果是评论
		if (req.body.blogId) {
			await commentCountChange(req.body.blogId);
		}

		res.send(sendResult(result));
	}

	// 通过id删除
	async remove(req, res, next) {
		const schema = req.joi
			.object({
				id: req.joi.string().regex(/^\d+$/)
			})
			.unknown(true);
		const { error: failed } = schema.validate(req.params);
		if (failed) return next(new AppError(failed, 400));
		// 获取评论的所属文章id
		const blogId = await getBlogId(req.params.id);

		// 删除操作
		const [error, result] = await to(removeService(req.params.id));
		if (error) return next(new AppError(error));

		// 如果删除成功,并且存在blogId
		if (blogId) {
			await commentCountChange(blogId, false);
		}

		res.send(sendResult(result));
	}

	// 通过文章id删除
	async removeByBlogId(req, res, next) {
		const [error, result] = await to(removeByBlogIdService(req.params.id));
		if (error) return next(new AppError(error, 400));

		// 删除成功
		await commentCountChange(req.params.id, false, 0);

		res.send(sendResult(result));
	}

	// 查询
	async findAll(req, res, next) {
		const schema = req.joi
			.object({
				blogId: req.joi.string().regex(/^\d+$/),
				size: req.joi.string().regex(/^\d+$/),
				limit: req.joi.string().regex(/^\d+$/)
			})
			.unknown(true);
		const { error: failed } = schema.validate(req.query);
		if (failed) return next(new AppError(failed, 400));

		await toi(findAll(req.query), res, next);
	}
}

/**
 * 通过评论id获取文章id
 * @param {*} id 评论id
 * @returns  文章id
 */
async function getBlogId(id) {
	const [blogErr, blogRes] = await to(findByIdService(id));
	if (blogErr) return;
	const blogId = blogRes?.blogId;
	return blogId;
}
module.exports = new BlogTypeController();
